<template>
  <div class="dept-manage">
    <!-- 查询区域 -->
    <el-form :inline="true" :model="searchForm" class="search-form" @submit.prevent>
      <el-form-item label="部门ID">
        <el-input v-model="searchForm.id" placeholder="请输入部门ID" clearable />
      </el-form-item>
      <el-form-item label="部门名称">
        <el-input v-model="searchForm.deptName" placeholder="请输入部门名称" clearable />
      </el-form-item>
      <el-form-item label="负责人">
        <el-input v-model="searchForm.manager" placeholder="请输入负责人" clearable />
      </el-form-item>
      <el-form-item label="办公楼栋">
        <el-input v-model="searchForm.placeBuilding" placeholder="请输入办公楼栋" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="showAddDialog = true">添加部门</el-button>
      </el-form-item>
    </el-form>

    <!-- 部门列表 -->
    <el-table :data="deptList" border>
      <el-table-column prop="id" label="部门ID" min-width="100" />
      <el-table-column prop="deptName" label="部门名称" min-width="120" />
      <el-table-column prop="manager" label="负责人" min-width="120" />
      <el-table-column prop="phone" label="联系电话" min-width="140">
        <template #default="{ row }">{{ row.phone || '-' }}</template>
      </el-table-column>
      <el-table-column prop="placeBuilding" label="办公楼栋" min-width="120" />
      <el-table-column prop="placeRoom" label="办公房间号" min-width="120" />
      <el-table-column prop="isDirect" label="是否直属部门" min-width="120">
        <template #default="{ row }">
          <el-tag :type="row.isDirect ? 'success' : 'info'">
            {{ row.isDirect ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="220">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="handleEditDept(row)">修改</el-button>
          <el-button size="small" type="danger" @click="handleDeleteDept(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      background
      layout="prev, pager, next, jumper, ->, total"
      :total="pagination.total"
      :page-size="pagination.size"
      :current-page="pagination.current"
      @current-change="handlePageChange"
    />

    <!-- 添加部门对话框 -->
    <el-dialog :title="editDeptId ? '修改部门' : '添加部门'" v-model="showAddDialog">
      <el-form :model="addForm" label-width="100px" :rules="formRules">
        <el-form-item label="部门名称" prop="deptName">
          <el-input v-model="addForm.deptName" />
        </el-form-item>
        <el-form-item label="负责人" prop="manager">
          <el-input v-model="addForm.manager" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="addForm.phone" placeholder="请输入11位手机号" />
        </el-form-item>
        <el-form-item label="办公楼栋" prop="placeBuilding">
          <el-input v-model="addForm.placeBuilding" />
        </el-form-item>
        <el-form-item label="办公房间号" prop="placeRoom">
          <el-input v-model="addForm.placeRoom" />
        </el-form-item>
        <el-form-item label="部门职责" prop="deptDuty">
          <el-input v-model="addForm.deptDuty" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="是否直属部门" prop="isDirect">
          <el-switch v-model="addForm.isDirect" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false; editDeptId = null">取消</el-button>
        <el-button type="primary" @click="handleSubmitDept">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios';

const searchForm = reactive({
  id: '',
  deptName: '',
  manager: '',
  placeBuilding: ''
})

const addForm = reactive({
  deptName: '',
  manager: '',
  phone: '',
  placeBuilding: '',
  placeRoom: '',
  deptDuty: '',
  isDirect: false
})

const formRules = reactive({
  deptName: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
  manager: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  placeBuilding: [{ required: true, message: '请输入办公楼栋', trigger: 'blur' }],
  placeRoom: [{ required: true, message: '请输入办公房间号', trigger: 'blur' }]
})

const deptList = ref([])
const pagination = reactive({
  total: 0,
  size: 10,
  current: 1
})
const showAddDialog = ref(false)
const editDeptId = ref<number | null>(null)

const fetchDepts = async (pageNum = 1) => {
  try {
    const params = {
      id: searchForm.id || null,
      deptName: searchForm.deptName || null,
      manager: searchForm.manager || null,
      placeBuilding: searchForm.placeBuilding || null
    }
    const res = await axios.post(
      import.meta.env.VITE_API_URL + `dept/page?pageNum=${pageNum}&pageSize=${pagination.size}`,
      params
    )
    deptList.value = res.data.records
    pagination.total = res.data.total
    pagination.current = res.data.current
    pagination.size = res.data.size
  } catch (e) {
    ElMessage.error('获取部门数据失败')
  }
}

const handleEditDept = (row: any) => {
  Object.assign(addForm, row)
  editDeptId.value = row.id
  showAddDialog.value = true
}

const handleDeleteDept = async (id: number) => {
  try {
    await axios.delete(import.meta.env.VITE_API_URL + `dept/${id}`)
    ElMessage.success('删除成功')
    fetchDepts(1)
  } catch (e) {
    ElMessage.error('删除失败')
  }
}

const handleSubmitDept = async () => {
  try {
    const url = editDeptId.value 
      ? import.meta.env.VITE_API_URL + 'dept/update'
      : import.meta.env.VITE_API_URL + 'dept/save'

    await axios.post(url, {
      ...addForm,
      id: editDeptId.value
    })

    ElMessage.success(editDeptId.value ? '修改成功' : '添加成功')
    showAddDialog.value = false
    editDeptId.value = null
    await fetchDepts(1)
  } catch (e) {
    ElMessage.error(editDeptId.value ? '修改失败' : '添加失败')
  }
}

const handleSearch = () => fetchDepts(1)
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    (searchForm as any)[key as keyof typeof searchForm] = ''
  })
  fetchDepts(1)
}
const handlePageChange = (page: number) => fetchDepts(page)

onMounted(() => {
  fetchDepts(1)
})
</script>

<style scoped>
@import '@/styles/views.css';
</style>